package autotd.bots;

import java.net.*;

import java.util.*;
import java.awt.Point;
import java.io.*;

import autotd.*;
import autotd.server.*;

public class JKBot extends Thread {
	public static final String[] towerMenu = { "BasicWater", "BasicFire", "BasicFire", "BasicLight" };
	public static final int[][] coordMenu = { {2,2}, {3,2}, {4,2}, {5,2} };
	
	SimulatorClient myCore;
	int menuPos;

	public JKBot(TDSimulator tdsim) throws Exception {
		myCore = new SimulatorClient(tdsim);
		menuPos = 0;
	}

	public void run() {
		while (myCore.getPlayer().isAlive()) {
			tryToBuy();
			tryToShoot();
			myCore.tick();
			try {
				Thread.sleep(100);
			} catch(Exception e) {
			}
		}
		System.out.println("I died!");
	}

	
	public void tryToBuy() {
		TowerType nextTower =  myCore.getTowerType(towerMenu[menuPos]);
		int cost = nextTower.Cost;
		while (myCore.getPlayer().getMoney() >= cost) {
			System.out.println("Trying to buy " + towerMenu[menuPos] + " at " + java.util.Arrays.toString(coordMenu[menuPos]));
			boolean result = myCore.placeTower(nextTower, coordMenu[menuPos][0], coordMenu[menuPos][1]);
			System.out.println(result);
			if (!result) {
				System.out.println("Why is PMoney = " + myCore.getPlayer().getMoney() + "?");
				break;
			}
			menuPos = (menuPos + 1) % towerMenu.length;
			nextTower =  myCore.getTowerType(towerMenu[menuPos]);
			cost = nextTower.Cost;
		}
	}

	public void tryToShoot() {
		Collection<Tower> towers = myCore.getPlacedTowers();
		Collection<Monster> monsters = new ArrayList<Monster>(myCore.getActiveMonsters());
		boolean somethingHappened;
		do {
			somethingHappened = false;
			for (Tower t : towers) {
				if (!t.ready()) {
					continue;
				}
				for (Monster m : monsters) {
					if (m.isDead() || !GameMap.inRange(t.pos, m.pos, t.Type.Range)) {
						continue;
					}
					//System.out.println("Trying to shoot " + m + " with " + t);
					boolean result = myCore.shootMonster(t.pos, m);
					//System.out.println(result);
					somethingHappened = result || somethingHappened;
					if (result) {
						break;
					}
				}
			}
		} while (somethingHappened);
	}


	
	
	
	public static void main(String[] args) throws Exception {
		TDSimulator sim = TDSimulator.getDefaultSimulator();
		if (sim == null) {
			System.err.println("Unable to load server settings. Please check to ensure that the file actually exists and has the correct format!");
			System.exit(-1);
		}
		JKBot bot = new JKBot(sim);
		bot.start();
	}
}









